import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {UrlService} from '../common/service/url.service';
import {Observable} from 'rxjs';
import {ApiRes} from '../common/model/response';
import {SearchResult} from '../content/model/search-result';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SearchResultService {

  constructor(private http: HttpClient,
              private urlService: UrlService) {
  }

  searchArticle(condition: SearchResult): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policySearch/search');
    return this.http.post<ApiRes>(url, condition).pipe(map(res => {
      if (res.result) {
        for (const policy of res.result.policys.list) {
          // 将多个发布机构拼成字符串，以顿号隔开
          const organs = [];
          for (const organ of policy.publishOrganList) {
            organs.push(organ.name);
          }
          policy.publishOrgans = organs.join('、');
        }
      }

      return res;
    }));

  }

  searchChecks(value: string, id: string = null): Observable<ApiRes> {
    let params = new HttpParams();
    if (value != null) {
      params = params.append('key', value);
    }
    if (id != null) {
      params = params.append('id', id);
    }

    const url = this.urlService.getWebUrl('/policySearch/getPolicySearchRequest');
    return this.http.get<ApiRes>(url, {params});

  }

  getTreeData(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policySearch/wordFreamList');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      // res.result = this.transformTree(res.result);
      return res;
    }));

  }

  // 将后台数据格式化成tree组件需要的数据格式
  transformTree(result: any) {
    const treeData = [];
    for (let i = 0; i < result.length; i++) {
      treeData.push({});
      treeData[i].title = result[i].name;
      treeData[i].key = result[i].id;
      treeData[i].isLeaf = !result[i].children.length;
      // if (result[i].children.length) {
      //   return treeData[i];
      // }
      treeData[i].children = [];
      treeData[i].children.push(this.transformTree(result[i].children));
    }

    return treeData;

  }
}
